A definitive guide to Lists, Tuples, and Dictionaries in Python with practical problem-solving applications.
Use ← → keys or swipe to navigate
Theory on Lists, Tuples, and Dictionaries.
Runner-up scores and Frequency counting.
Key-Value bindings for Movies and Students.
Creating Contact Book and To-do Manager loops.
Lists are used to store multiple items in a single variable. They are ordered, mutable (changeable), and allow duplicate values.
# Creating a list fruits = ["apple", "banana", "cherry"] # Mutating a list fruits.append("orange") # Adds to the end fruits[1] = "mango" # Modifies index 1 fruits.pop(0) # Removes item at index 0 print(fruits) # Output: ['mango', 'cherry', 'orange']
Items have a defined order, which will not change. If you add new items, they are placed at the end.
We can change, add, and remove items in a list after it has been created.
Tuples are identical to lists, but with one critical difference: they are immutable (unchangeable). Once a tuple is created, you cannot change its values.
# Creating a tuple coordinates = (10.5, 20.8) # Tuples can be accessed like lists print(coordinates[0]) # Output: 10.5 # ERROR: coordinates[0] = 11.5 # "tuple object does not support item assignment"
Dictionaries are used to store data values in key:value pairs. They are ordered (as of Python 3.7), changeable, and do NOT allow duplicate keys.
# Creating a dictionary car = { "brand": "Ford", "model": "Mustang", "year": 1964 } # Accessing attributes via keys print(car["brand"]) # Output: Ford car["year"] = 2020 # Updates value
.get('key') is safer than [] because it avoids KeyErrors if missing.Task: Scan n values in the range 0-3 and print the number of times each value has occurred.
n = int(input("Enter number of values to read: ")) values = [] for i in range(n): val = int(input("Enter a value (0-3): ")) if 0 <= val <= 3: values.append(val) else: print("Ignored: Value must be between 0 and 3.") # Check count for 0, 1, 2, 3 for x in range(4): freq = values.count(x) print(f"Value {x} occurred {freq} times")
Task: Create a tuple to store n numeric values and find the average of all values.
n = int(input("Enter number of values: ")) temp_list = [] # Lists are easier to build dynamically than Tuples for i in range(n): num = float(input("Enter numeric value: ")) temp_list.append(num) # Convert list to tuple num_tuple = tuple(temp_list) if len(num_tuple) > 0: avg = sum(num_tuple) / len(num_tuple) print(f"Tuple: {num_tuple}") print(f"Average: {avg:.2f}")
Because tuples are immutable, you cannot use .append() on them. A common pattern is appending to a temporary List and type-casting it to a Tuple at the very end using the tuple() constructor.
Task: Input a list of scores for N students. Find the score of the runner-up.
n = int(input("N = ")) input_string = input("Scores= ") # The split() splits the string by spaces. # List comprehension converts strings to integers. scores = [int(x) for x in input_string.split()] # Remove duplicates to handle multiple maximum scores unique_scores = list(set(scores)) # Sort in descending order unique_scores.sort(reverse=True) # The 0th index is highest, 1st index is runner-up print(unique_scores[1])
Task: Create a dictionary linking Names (keys) to Cities (values) and execute multiple queries.
persons = {"Alice": "Paris", "Bob": "London", "Charlie": "Paris"} # a) Display all names (Keys) print("Names:", list(persons.keys())) # b) Display all cities (Values) print("Cities:", list(persons.values())) # c) Display student name and city for name, city in persons.items(): print(f"{name} -> {city}") # d) Count number of students in each city city_count = {} for city in persons.values(): # .get(city, 0) handles cases where city key is not made yet city_count[city] = city_count.get(city, 0) + 1 print("Counts:", city_count)
Task: Create a dictionary holding another dictionary (Name -> {Year, Director, Cost, Earnings}). Query specific movies.
movies = { "Inception": {"year":2010, "dir":"Nolan", "cost":160, "earn":836}, "Avatar": {"year":2009, "dir":"Cameron","cost":237, "earn":2900}, "Dune": {"year":2021, "dir":"Villeneuve","cost":165, "earn":400} } print("--- Movies Before 2015 ---") for name, info in movies.items(): if info["year"] < 2015: print(name) print("--- Movies Making Profit ---") for name, info in movies.items(): if info["earn"] > info["cost"]: print(name) print("--- Movies by Nolan ---") for name, info in movies.items(): if info["dir"] == "Nolan": print(name)
Task: Create a persistent CRUD (Create, Read, Update, Delete) program using a Dictionary.
contacts = {} while True: ch = int(input("1.Add 2.Search 3.Delete 4.Exit : ")) if ch == 1: name = input("Name: ") contacts[name] = input("Phone: ") elif ch == 2: name = input("Name to search: ") print("Found:", contacts.get(name, "Not Found")) elif ch == 3: name = input("Name to delete: ") if name in contacts: del contacts[name] print("Deleted.") elif ch == 4: break
Task: Create an infinite loop permitting users to push and pop tasks out of a List array.
todos = [] while True: print("1.Add Task 2.View Tasks 3.Remove Task 4.Exit") ch = int(input("Choice: ")) if ch == 1: todos.append(input("Enter new task: ")) elif ch == 2: for idx, task in enumerate(todos): print(f"Task {idx+1}: {task}") elif ch == 3: idx = int(input("Enter Task Number to Remove: ")) - 1 if 0 <= idx < len(todos): removed = todos.pop(idx) print(f"{removed} successfully removed.") else: print("Invalid ID.") elif ch == 4: break
Understanding Data Structures is arguably the most important step of python scripting. It is imperative to perform these labs yourself.